#!/bin/bash
# auth: fearless11
# date: 2024/9/14

# helm -n monitor-exporter uninstall xxx
# helm -n monitor-exporter list

# https://github.com/prometheus-community/helm-charts
# https://github.com/prometheus-community/helm-charts/releases
helm_prometheus() {
    mkdir -p /prometheus && cd /prometheus

    helm repo add grafana https://grafana.github.io/helm-charts
    helm repo add prometheus-community https://prometheus-community.github.io/helm-charts

    helm pull grafana/grafana
    helm pull prometheus-community/prometheus
    helm pull prometheus-community/prometheus-mysql-exporter
    helm pull prometheus-community/prometheus-redis-exporter
    helm pull prometheus-community/prometheus-kafka-exporter
    helm pull prometheus-community/prometheus-rabbitmq-exporter

    kubectl create ns monitor
    helm install prometheus -n monitor /prometheus/grafana
}

helm_exporter_install() {

    while read line; do
        echo $line | grep '^#' && continue

        name=$(echo $line | awk -F, '{print $1}')
        addr=$(echo $line | awk -F, '{print $2}')
        biz=$(echo $line | awk -F, '{print $3}')
        user=$(echo $line | awk -F, '{print $4}')
        passwd=$(echo $line | awk -F, '{print $5}')

        if [[ X$name == "Xredis" ]]; then
            sed -e "s/127.0.0.1:6379/$addr/g;s/xbiz/$biz/g;s/xpasswd/$passwd/g" prometheus-redis-exporter/values.yaml >/tmp/redis.yaml
            helm -n monitoring install $biz prometheus-redis-exporter -f /tmp/redis.yaml
            # helm -n monitoring install $biz prometheus-redis-exporter -f /tmp/redis.yaml --dry-run
        elif [[ X$name == "Xkafka" ]]; then
            sed -e "s/127.0.0.1:9092/$addr/g;s/xbiz/$biz/g" prometheus-kafka-exporter/values.yaml >/tmp/kafka.yaml
            helm -n monitoring install $biz prometheus-kafka-exporter -f /tmp/kafka.yaml
            # helm -n monitoring install $biz prometheus-kafka-exporter -f /tmp/kafka.yaml --dry-run
        fi
    done <exporter.conf

    rm -rf /tmp/redis.yaml /tmp/kafka.yaml
}

helm_exporter_uninstall() {

    while read line; do
        echo $line | grep '^#' && continue
        biz=$(echo $line | awk -F, '{print $3}')
        helm -n monitoring uninstall $biz
    done <exporter.conf
}

helm_exporter_ls() {
    helm -n monitoring ls
}

case "${1}" in
install)
    helm_exporter_install
    ;;
uninstall)
    helm_exporter_uninstall
    ;;
ls)
    helm_exporter_ls
    ;;
*)
    echo "$0 install|uninstall|ls"
    ;;
esac
